<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程名称" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入课程名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="讲师" prop="Lecturer">
        <el-input v-model="queryParams.Lecturer" placeholder="请输入讲师" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <md-select-tree v-model="queryParams.categoryId" :defaultExpandAll="true" :data="parentList" nodeKey="rid" :defaultProps="{label:'name',children:'categoryList'}" placeholder="请选择上级"></md-select-tree>
      </el-form-item>
      <el-form-item label="是否推荐" prop="isNominate">
        <el-select v-model="queryParams.isNominate" placeholder="是否推荐" clearable>
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="2"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="是否首页" prop="isHome">
        <el-select v-model="queryParams.isHome" placeholder="是否首页" clearable>
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="2"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option label="显示" value="1"></el-option>
          <el-option label="隐藏" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:video:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:user:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column label="编号" align="left" prop="rid" width="50" />
      <el-table-column label="封面" align="left" prop="cover" min-width="150">
        <template slot-scope="{ row }">
          <div class="cover" style="width: 80px;">
            <img :src="`${api}${row.cover}`" style="display: block; width: auto; height: auto; max-width: 100%; max-height: 100%; margin:0px auto;" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="课程名称" align="left" prop="title" min-width="200" />

      <el-table-column label="讲师" align="left" prop="lecturer" width="100" />
      <el-table-column label="序号" align="left" prop="sort" width="100" />
      <el-table-column label="访问量" align="left" prop="viewTotal" width="100" />
      <el-table-column label="虚拟访问量" align="left" prop="viewTotalVirtual" width="100" />
      <el-table-column label="点赞数" align="left" prop="giveLikeTotal" width="100" />
      <el-table-column label="虚拟点赞数" align="left" prop="giveLikeTotalVirtual" width="100" />

      <el-table-column label="是否推荐" align="left" prop="isNominate" width="100">
        <template slot-scope="{ row }">
          <span v-if="row.isHome==='1'">是</span>
          <span v-if="row.isHome==='2'">否</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否首页" align="left" prop="isHome" width="100">
        <template slot-scope="{ row }">
          <span v-if="row.isHome==='1'">是</span>
          <span v-if="row.isHome==='2'">否</span>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" align="left" prop="status" width="100">
        <template slot-scope="{ row }">
          <span v-if="row.status==='1'">显示</span>
          <span v-if="row.status==='2'">隐藏</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:video:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:video:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleOutline(scope.row)" v-hasPermi="['system:video:remove']">大纲管理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改视频对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-row style="height: 500px;">
        <el-col :span="5" style="border-right: 1px solid #efefef; height: 500px; overflow-x: hidden; overflow-y: auth;" v-loading="categoryLoading">
          <p>请选择课程分类</p>
          <el-tree ref="mdCategory" :data="parentList" node-key="rid" :props="{label:'name',children:'categoryList'}" highlight-current @node-click="handleCatrgoryClick">
          </el-tree>
        </el-col>
        <el-col :span="19" style="height: 500px; overflow-x: hidden; overflow-y: auth; padding-left: 20px; padding-right: 20px;">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="top">
            <el-form-item label="课程名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入视频名称" />
            </el-form-item>
            <el-form-item label="封面" prop="cover">
              <ImageUpload v-model="form.cover" :limit="1" />
            </el-form-item>
            <el-form-item label="讲师" prop="lecturer">
              <el-input v-model="form.lecturer" placeholder="请输入讲师" />
            </el-form-item>
            <el-form-item label="课程序号" prop="sort">
              <el-input  type="number" v-model="form.sort" placeholder="请输入数字" />
            </el-form-item>
            <el-form-item label="简介" prop="synopsis">
              <editor v-model="form.synopsis" :min-height="192" />
            </el-form-item>
            <!-- <el-form-item label="课程时间" prop="courseTime">
              <el-date-picker v-model="form.courseTime" type="daterange" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="学习安排" prop="learningArrangement">
              <el-input v-model="form.learningArrangement" placeholder="请输入学习安排" />
            </el-form-item> -->
            <el-form-item label="访问量" prop="viewTotal">
              <el-input v-model="form.viewTotal" type="number" placeholder="请输入访问量" />
            </el-form-item>
            <el-form-item label="虚拟访问量" prop="viewTotalVirtual">
              <el-input v-model="form.viewTotalVirtual" type="number" placeholder="请输入虚拟访问量" />
            </el-form-item>
            <el-form-item label="点赞数" prop="giveLikeTotal">
              <el-input v-model="form.giveLikeTotal" type="number" placeholder="请输入点赞数" />
            </el-form-item>
            <el-form-item label="虚拟点赞数" prop="giveLikeTotalVirtual">
              <el-input v-model="form.giveLikeTotalVirtual" type="number" placeholder="请输入虚拟点赞数" />
            </el-form-item>
            <el-form-item label="是否推荐" prop="isNominate">
              <el-radio-group v-model="form.isNominate">
                <el-radio label="1">是</el-radio>
                <el-radio label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- <el-form-item label="是否首页" prop="isHome">
              <el-radio-group v-model="form.isHome">
                <el-radio label="1">是</el-radio>
                <el-radio label="2">否</el-radio>
              </el-radio-group>
            </el-form-item> -->
            <el-form-item label="是否显示" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="1">是</el-radio>
                <el-radio label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title1" :visible.sync="open1" width="1000px" append-to-body :close-on-click-modal="false">
      <el-form ref="form1" :model="form" :rules="rules1" label-width="100px" label-position="left">
        <div v-for="(item, index) in form.videoOutlineList" :key="index" style="border-bottom: 1px solid #efefef; margin-bottom: 20px;">
          <el-row>
            <el-col :span="19" style="border-right: 1px solid #efefef; padding-right: 20px;">
              <el-form-item :prop="`videoOutlineList.${index}.title`" :rules="rules1.title" label="章节名称：">
                <el-input v-model="item.title" placeholder="请输入章节名称" />
              </el-form-item>
              <el-form-item :prop="`videoOutlineList.${index}.introduce`" :rules="rules1.introduce" label="章节介绍：">
                <el-input v-model="item.introduce" type="textarea" placeholder="请输入章节介绍" />
              </el-form-item>

              <el-form-item label-width="0px">
                <el-form :ref="`form2${index}`" :model="item" :rules="rules2" label-width="100px" label-position="left">
                  <div v-for="(sub, subIndex) in item.videoOutineDetails" :key="`${index}-${subIndex}`" style="margin-left: 100px; margin-bottom: 20px; border-bottom: 1px solid #efefef; padding-bottom: 20px;">
                    <el-row>
                      <el-col :span="19">
                        <el-form-item :prop="`videoOutineDetails.${subIndex}.name`" :rules="rules2.name" label="视频名称：" style="margin-bottom: 20px;">
                          <el-input v-model="sub.name" placeholder="请输入视频名称" />
                        </el-form-item>
                        <el-form-item :prop="`videoOutineDetails.${subIndex}.type`" :rules="rules2.type" label="上传类型：" style="margin-bottom: 20px;">
                          <el-radio-group v-model="sub.type">
                            <el-radio :label="1">选择本地视频</el-radio>
                            <el-radio :label="2">地址输入</el-radio>
                          </el-radio-group>
                        </el-form-item>
                        <el-form-item :prop="`videoOutineDetails.${subIndex}.url`" :rules="rules2.url" label="视频地址：" v-if="sub.type===1">
                          <FileUpload v-model="sub.url" :limit="1" :fileSize="5000" :fileType="['mp4']" />
                        </el-form-item>
                        <el-form-item :prop="`videoOutineDetails.${subIndex}.url`" :rules="rules2.url" label="视频地址：" v-if="sub.type===2">
                          <el-input v-model="sub.url" placeholder="请输入视频地址" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="5" style="padding: 0px !important; text-align: right">
                        <el-button type="danger" size="small" @click="handleDelShiPin(item, sub, index, subIndex);" v-if="item.videoOutineDetails.length>1">删除视频</el-button>
                        <el-button type="primary" size="small" v-if="subIndex===item.videoOutineDetails.length-1" @click="handleAddShiPin(item, sub, index, subIndex);">新增视频</el-button>
                      </el-col>
                    </el-row>
                  </div>
                </el-form>
              </el-form-item>

            </el-col>
            <el-col :span="5" style="padding: 0px !important; text-align: right">
              <el-button type="danger" size="small" @click="handleDelZhangJie(item, index);" v-if="form.videoOutlineList.length>1">删除章节</el-button>
              <el-button type="primary" size="small" v-if="index===form.videoOutlineList.length-1" @click="handleAddZhangJie(item, index);">新增章节</el-button>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(1)">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVideo, getVideo, delVideo, addVideo, updateVideo, delZhangJie, delShiPin } from "@/api/web/video";
import { listCategory } from "@/api/web/category";
import { api } from '@/utils/config.js'
export default {
  name: "Video",
  data () {
    return {
      api,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频表格数据
      videoList: [],
      // 弹出层标题
      title: "",
      title1: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        isNominate: null,
        isHome: null,
        status: null,
        Lecturer: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "视频名称不能为空", trigger: "blur" }
        ],
        cover: [
          { required: true, message: "请上传视频封面", trigger: "change" }
        ],
        synopsis: [
          { required: true, message: "简介不能为空", trigger: "blur" }
        ],
        lecturer: [
          { required: true, message: "讲师不能为空", trigger: "blur" }
        ],
        // courseTime: [
        //   {
        //     required: true, message: "请选择课程时间", validator: (rule, value, callback) => {
        //       if (value.length === 0) {
        //         callback(new Error('请选择课程时间'))
        //       } else {
        //         callback()
        //       }
        //     }, trigger: "blur"
        //   }
        // ],
        // learningArrangement: [
        //   { required: true, message: "学习安排不能为空", trigger: "blur" }
        // ]
      },
      rules1: {
        title: [
          { required: true, message: "章节名称不能为空", trigger: "blur" }
        ],
        introduce: [
          { required: true, message: "章节介绍不能为空", trigger: "blur" }
        ],
      },
      rules2: {
        name: [
          { required: true, message: "视频名称不能为空", trigger: "blur" }
        ],
        url: [
          { required: true, message: "视频地址不能为空", trigger: "blur" }
        ]
      },
      parentList: [],
      categoryLoading: false
    };
  },
  created () {
    this.getList();
    this.getParentList(true)
  },
  methods: {
    /** 查询视频列表 */
    getList () {
      this.loading = true;
      listVideo(this.queryParams).then(response => {
        this.videoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询分类列表 */
    getParentList (flag) {
      this.categoryLoading = true
      listCategory({
        type: 1
      }).then(response => {
        this.parentList = response.data;
        if (!flag) {
          this.$nextTick(() => {
            setTimeout(() => {
              if (this.form.categoryId) {
                this.$refs.mdCategory.setCurrentKey(this.form.categoryId)
              }
              const nodesMap = this.$refs.mdCategory.store.nodesMap
              const keys = Object.keys(nodesMap)
              keys.forEach(key => {
                nodesMap[key].expanded = true
              })
              this.categoryLoading = false
            }, 500);
          })
        }
      });
    },
    handleCatrgoryClick (event) {
      this.form.categoryId = event['rid']
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.open1 = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        rid: null,
        categoryId: null,
        title: null,
        synopsis: null,
        videoContent: null,
        videoUrl: null,
        cover: null,
        viewTotal: 0,
        viewTotalVirtual: 0,
        giveLikeTotal: 0,
        giveLikeTotalVirtual: 0,
        isNominate: '1',
        isHome: '1',
        status: '1',
        videoType: null,
        lecturer: null,
        courseTime: [],
        learningArrangement: null,
        createTime: null,
        updateTime: null,
        videoOutlineList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.rid)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.getParentList()
      this.title = "添加课程";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const rid = row.rid || this.ids
      getVideo(rid).then(response => {
        this.form = response.data;
        this.form.courseTime = response.data.courseTime.split(',')
        this.form.viewTotal = parseInt(response.data.viewTotal)
        this.form.viewTotalVirtual = parseInt(response.data.viewTotalVirtual)
        this.form.giveLikeTotal = parseInt(response.data.giveLikeTotal)
        this.form.giveLikeTotalVirtual = parseInt(response.data.giveLikeTotalVirtual)
        this.open = true;
        this.getParentList()
        this.title = "修改课程";
      });
    },
    /** 大纲管理 */
    handleOutline (row) {
      this.reset()
      this.form.videoOutlineList = []

      const rid = row.rid || this.ids
      getVideo(rid).then(response => {
        this.form = response.data;
        const videoOutlineList = response.data.videoOutlineList || [
          {
            title: null,
            introduce: null,
            videoOutineDetails: [
              {
                type: 1, // 1上传 2地址
                name: null,
                url: null
              },
              {
                type: 1, // 1上传 2地址
                name: null,
                url: null
              }
            ]
          }
        ]
        if (videoOutlineList.length === 0) {
          this.form.videoOutlineList = [
            {
              title: null,
              introduce: null,
              videoOutineDetails: [
                {
                  type: 1, // 1上传 2地址
                  name: null,
                  url: null
                }
              ]
            }
          ]
        }

        this.open1 = true
        this.title1 = "大纲管理";
      });
    },
    handleDelZhangJie (row, index) {
      console.log(row,'row');
      if (row.rid) {
        // 执行接口删除逻辑
        const rids =row.rid;
        this.$modal.confirm('确定要删除吗，同时会删除章节下的所有视频？').then(function () {
          return delZhangJie(rids);
        }).then(() => {
          this.form.videoOutlineList.splice(index, 1)
        }).catch(() => { });
      } else {
        this.form.videoOutlineList.splice(index, 1)
      }
    },
    handleAddZhangJie (row, index) {
      this.form.videoOutlineList.push({
        title: null,
        introduce: null,
        videoOutineDetails: [
          {
            type: 1, // 1上传 2地址
            name: null,
            url: null
          }
        ]
      })
    },
    handleDelShiPin (row, subRow, index, subIndex) {
      if (subRow.rid) {
        // 执行接口删除逻辑
        const rids = row.rid
        this.$modal.confirm('确定要删除视频吗？').then(function () {
          return delShiPin(rids);
        }).then(() => {
          row.videoOutineDetails.splice(subIndex, 1)
        }).catch(() => { });
      } else {
        row.videoOutineDetails.splice(subIndex, 1)
      }
    },
    handleAddShiPin (row, subRow, index, subIndex) {
      row.videoOutineDetails.push({
        type: 1, // 1上传 2地址
        name: null,
        url: null
      })
    },
    /** 提交按钮 */
    async submitForm (type) {
      const params = Object.assign({}, { ...this.form })

      if (!params.categoryId) {
        this.$modal.msgWarning("请选择在左侧课程分类");
        return
      }

      const forms = []
      if (type === 1) {
        forms.push('form1')
        if (params.videoOutlineList.length > 0) {
          for (let index = 0; index < params.videoOutlineList.length; index++) {
            forms.push(`form2${index}`)
          }
        }
      } else {
        forms.push('form')

        params.courseTime = params.courseTime.join(',')

        if (!params.viewTotal) {
          params.viewTotal = '0'
        }

        if (!params.viewTotalVirtual) {
          params.viewTotalVirtual = '0'
        }

        if (!params.giveLikeTotal) {
          params.giveLikeTotal = '0'
        }

        if (!params.giveLikeTotalVirtual) {
          params.giveLikeTotalVirtual = '0'
        }
      }

      let valid = false

      for (let index = 0; index < forms.length; index++) {
        const form = forms[index];
        try {
          await ((this.$refs[form] instanceof Array) ? this.$refs[form][0] : this.$refs[form]).validate()
          valid = true
        } catch (error) {
          console.log(error)
          valid = false
        }
      }

      if (!valid) {
        return
      }

      if (params.rid != null) {
        updateVideo(params).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.open1 = false;
          this.getList();
        });
      } else {
        addVideo(params).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.open1 = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    async handleDelete (row) {
      const rids = row.rid || this.ids;
      try {
        await this.$modal.confirm('是否确认删除视频编号为"' + rids + '"的数据项？')

        delVideo(rids)
        delDeptVideo(rids)
        this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch (error) {
        console.log(error)
      }
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('system/video/export', {
        ...this.queryParams
      }, `video_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
